package com.intramirror.wd.service.security.model.token;

import com.google.common.collect.Lists;
import com.intramirror.wd.business.util.CheckUtils;
import com.intramirror.wd.business.util.SpringUtils;
import com.intramirror.wd.service.security.exceptions.ExpiredTokenException;
import com.intramirror.wd.service.security.model.UserContext;
import com.intramirror.wd.service.security.model.UserRole;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * Created by juzhongzheng on 2018/5/3.
 */
public class AccessTokenTimeCheck {
    private static Long tokenAccessTime = 2*60*60*1000L; // 2小时
    private static Map<String,Long> tokenAccessTimeMap = new HashMap<>(); // key token value last access time
    private static String unAuthToken = null;  // 一年有效期
    private static TokenFactory tokenFactory;
    static {
        if(tokenFactory == null){
            tokenFactory = SpringUtils.getBean("tokenFactory");
        }
    }
    public static void checkTime(String token) throws ExpiredTokenException {
        if(token == null) throw new  ExpiredTokenException("Token is null");
        if(token.equals(unAuthToken)){ // unAuthToken 不用校验
            return;
        }
        Long lassAccess = tokenAccessTimeMap.get(token);
        if(lassAccess == null){
            tokenAccessTimeMap.put(token,System.currentTimeMillis());
        }else {
            if(System.currentTimeMillis() - lassAccess > tokenAccessTime){
                throw new ExpiredTokenException("Login was timeout! Please login again!");
            }else {
                tokenAccessTimeMap.put(token,System.currentTimeMillis());
            }
        }
    }
    public static String getNuAuthToken(){
        List<UserRole> roles = Lists.newArrayList(new UserRole("ROLE_ADMIN"));
        List<GrantedAuthority> authorities = roles.stream()
                .map(authority -> new SimpleGrantedAuthority(authority.authority()))
                .collect(Collectors.toList());


        UserContext context = UserContext.create("admin", authorities);
        if(CheckUtils.isBlank(unAuthToken)){
            AccessToken token = tokenFactory.createEffectiveAccess(context);
            unAuthToken = token.getToken();
        }
        return unAuthToken;
    }
}
